<template>
  <el-container style="border: 1px solid #eee;">
    <el-aside width="310">
      <el-radio-group v-if="false" v-model="isCollapse" style="margin-bottom: 20px;">
        <el-radio-button :label="false">展开</el-radio-button>
        <el-radio-button :label="true">收起</el-radio-button>
      </el-radio-group>
      <el-menu default-active="0-0" class="el-menu-vertical-demo" :collapse="isCollapse" :unique-opened="true" @open="handleOpen" @close="handleClose">
        <el-submenu v-for="(item, k, idx) in groupData" :key="idx" :index="idx + ''">
          <template slot="title">
            <i :class="item.clazz" />
            <span slot="title">{{ item.name }}[{{ item.items.length }}]项</span>
          </template>
          <el-menu-item v-for="(item2, idx2) in item.items" :key="idx2" :index="myIdx(idx, idx2) + ''" :title="item2.fileName" @click="preview(k, item.items, item2.url)">
            <a :href="item2.url" :download="item2.fileName" title="下载" @click="download"><i class="el-icon-download" /></a>
            <span ref="menu">{{ item2.fileName }}</span>
            <span style="display: none">{{ item2.contentType }}</span>
            <span style="display: none">{{ item2.fileSizeInfo }}</span>
            <span style="display: none">{{ item2.url }}</span>
          </el-menu-item>
        </el-submenu>
      </el-menu>
    </el-aside>
    <el-main style="display: flex;padding: 0">
      <iframe v-if="showFrame" id="myiframe" :src="iframeSrc" width="100%" @lοad="changeFrameHeight()" />
    </el-main>
  </el-container>
</template>
<script>
import { courseChapterPeriodattAchmentDetail } from '@/api/course'
export default {
  async asyncData(context) {
    try {
      const result = {}
      result.postData = await courseChapterPeriodattAchmentDetail({ id: context.params.id })
      // console.log('postData', result.postData)
      // console.log('postData.attachmentContentTypes', result.postData.attachmentContentTypes)

      result.groupData = {
        'image': { name: '图片', clazz: 'el-icon-picture', items: [] },
        'application': { name: '文档', clazz: 'el-icon-document', items: [] },
        'video': { name: '视频', clazz: 'el-icon-video-play', items: [] },
        'other': { name: '其它', clazz: 'el-icon-location', items: [] }
      }

      try {
        const _nameMap = {}
        const _attachments = result.postData.attachments
        if (_attachments && _attachments.length > 2) {
          const _attachmentArray = JSON.parse(_attachments)
          for (const i in _attachmentArray) {
            const item = _attachmentArray[i]
            _nameMap[item.fileName] = item
          }
        }
        // console.log('_attachments', _attachments)
        // console.log('_nameMap', _nameMap)

        const contentTypes = result.postData.attachmentContentTypes
        for (const key in contentTypes) {
          // key 为文件名
          // val 为 contentType
          const val = contentTypes[key]
          // groupTypePrefix 为 contentType 前缀
          const groupTypePrefix = val.indexOf('/') > 0 ? val.substring(0, val.indexOf('/')) : val
          const url = _nameMap[key].url
          const fileSize = _nameMap[key].fileSize
          let fileSizeInfo = ''
          if (fileSize > 1024 * 1024) {
            fileSizeInfo = (fileSize / (1024 * 1024)).toFixed(2) + ' MB'
          } else {
            fileSizeInfo = (fileSize / (1024)).toFixed(2) + ' KB'
          }

          const childItem = { fileName: key, url: url, contentType: val, fileSizeInfo: fileSizeInfo }
          if (result.groupData[groupTypePrefix]) {
            result.groupData[groupTypePrefix].items.push(childItem)
          } else {
            result.groupData.other.items.push(childItem)
          }
          // console.log('childItem', childItem)
        }

        // 删除子项为空的数据项
        const _dels = []
        for (const key in result.groupData) {
          if (result.groupData[key].items.length === 0) {
            _dels.push(key)
          }
        }
        for (const i in _dels) {
          const key = _dels[i]
          delete result.groupData[key]
          // console.log('delKey', key)
        }
        // console.log('result.groupData', result.groupData)
      } catch (e) {
        console.error(e)
        context.error({ message: 'Data not found', statusCode: 404 })
      }
      return result
    } catch (e) {
      console.error(e)
      context.error({ message: 'Data not found', statusCode: 404 })
    }
  },
  data() {
    return {
      isCollapse: false,
      iframeSrc: '',
      showFrame: false
    }
  },
  mounted() {
    this.$refs.menu[0].parentElement.click()
    // this.$refs.menu[0].click()
  },
  methods: {
    myIdx: function(idx1, idx2) {
      return idx1 + '-' + idx2
    },
    handleOpen(key, keyPath) {
      console.log(key, keyPath)
    },
    handleClose(key, keyPath) {
      console.log(key, keyPath)
    },
    changeFrameHeight() {
      const iframe = document.getElementById('myiframe')
      iframe.height = iframe.contentDocument.body.clientHeight
    },
    preview(groupContentType, groupUrls, url) {
      this.showFrame = false
      // 不带端口信息
      let websiteDomain = window.document.domain
      // kkfileview 端口号为 8012
      websiteDomain = websiteDomain + ':' + 8012
      websiteDomain = window.location.protocol + '//' + websiteDomain + '/'

      let previewUrl = ''
      if (groupContentType === 'image') {
        const arr = []
        for (const i in groupUrls) {
          const item = groupUrls[i]
          arr.push(item.url)
        }
        previewUrl = arr.join('|')
        previewUrl = window.Base64.encode(previewUrl)
        const currentUrl = window.Base64.encode(url)
        this.iframeSrc = websiteDomain + 'picturesPreview?urls=' + encodeURIComponent(previewUrl) + '&currentUrl=' + encodeURIComponent(currentUrl)
      } else {
        previewUrl = window.Base64.encode(url)
        this.iframeSrc = websiteDomain + 'onlinePreview?url=' + encodeURIComponent(previewUrl)
      }
      this.showFrame = true
    },
    download(event) {
      event.stopPropagation()
    }
  }
}
</script>
<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 300px;
  height: calc(100vh);
}
.el-menu-item {
  overflow: hidden;
  text-overflow: ellipsis;
}
.el-submenu__title {
  /* border-bottom: 1px solid #F2F2F2; */
}
</style>
